package elitech.vietnam.weatherfashion.tabs;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.libs.multicolumlist.internal.PLA_AdapterView;

public abstract class AbstractFragment extends Fragment {

	protected View	progress_loading, layout_main, image_nodata, root;

	public void onLoading(boolean state) {
		if (state) {
			progress_loading.setVisibility(View.VISIBLE);
			layout_main.setVisibility(View.INVISIBLE);
		} else {
			progress_loading.setVisibility(View.INVISIBLE);
			layout_main.setVisibility(View.VISIBLE);
		}
	}

	public void onNoData(boolean state) {
		if (state) {
			image_nodata.setVisibility(View.VISIBLE);
			layout_main.setVisibility(View.INVISIBLE);
		} else {
			image_nodata.setVisibility(View.INVISIBLE);
			layout_main.setVisibility(View.VISIBLE);
		}
	}

	public void setupView(View root) {
		this.root = root.findViewById(R.id.root);
		progress_loading = root.findViewById(R.id.progress_loading);
		layout_main = root.findViewById(R.id.layout_main);
		image_nodata = root.findViewById(R.id.image_nodata);
	}

	@Override
	public void onDestroyView() {
		unbindDrawables(root);
		super.onDestroyView();
		System.gc();
	}

	@Override
	public void onResume() {
		super.onResume();

		/*
		 * Return to current tab root if requested
		 */
		if (getActivity().getIntent().getIntExtra("RETURN_ROOT", -1) > 0) {
			BaseContainerFragment base = ((MainActivity) getActivity()).getCurrentBase();
			if (base != null)
				base.popAllFragment();
			getActivity().getIntent().removeExtra("RETURN_ROOT");
		}

		/*
		 * Hide soft keyboard
		 */
		try {
			InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(getActivity().getWindow().getCurrentFocus().getWindowToken(), 0);
		} catch (Exception e) {}
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	private void unbindDrawables(View view) {
		if (view == null)
			return;
		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
		}
		if (view instanceof ImageView)
			if (((ImageView) view).getDrawable() != null)
				((ImageView) view).getDrawable().setCallback(null);
		if (view instanceof ViewGroup && !(view instanceof AdapterView) && !(view instanceof PLA_AdapterView)) {
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				unbindDrawables(((ViewGroup) view).getChildAt(i));
			}
			((ViewGroup) view).removeAllViews();
		}
	}
}